package dtd.PHS.VND_ExchangeRate;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.FrameLayout.LayoutParams;
import dtd.PHS.VND_ExchangeRate.data.DataProvider;
import dtd.PHS.VND_ExchangeRate.data.MyDate;
import dtd.PHS.VND_ExchangeRate.data.RateItem;
import dtd.PHS.VND_ExchangeRate.data.SJCItem;
import dtd.PHS.VND_ExchangeRate.data.UpdateGoldService;
import dtd.PHS.VND_ExchangeRate.ui.CalculatorView;
import dtd.PHS.VND_ExchangeRate.ui.InOutAnimation;
import dtd.PHS.VND_ExchangeRate.ui.ListRatesView;
import dtd.PHS.VND_ExchangeRate.ui.MyMainMenu;
import dtd.PHS.VND_ExchangeRate.ui.RequestableFrameLayout;
import dtd.PHS.VND_ExchangeRate.ui.SendSmsView;
import dtd.PHS.VND_ExchangeRate.ui.ShareGoldPriceDialog;
import dtd.PHS.VND_ExchangeRate.ui.ShareListRateDialog;
import dtd.PHS.VND_ExchangeRate.ui.gesture.GestureActivity;
import dtd.PHS.VND_ExchangeRate.utils.ApplicationContext;
import dtd.PHS.VND_ExchangeRate.utils.Helpers;
import dtd.PHS.VND_ExchangeRate.utils.Logger;
import dtd.PHS.VND_ExchangeRate.utils.MyHandler;

public class MainActivity extends GestureActivity {

	private TextView tvTitle;
	private ImageButton[] tabs;
	private int lastSeenTabId;
	private int currentTabId;

	/** Called when the activity is first created. */
	private MyMainMenu mainMenu;
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.main_act);
	    Helpers.changeLanguage(this,Helpers.getLanguagePreference());
	    createViews();
	    mainMenu = new MyMainMenu(this);
	    restoreLastShareRate(savedInstanceState);
	}

	private void restoreLastShareRate(Bundle savedInstanceState) {
		if ( savedInstanceState == null ) return;
		String previousChoosenRate = savedInstanceState.getString(SHARE_RATE_ITEM);
	    if ( previousChoosenRate != null )
	    	shareRate = new RateItem(previousChoosenRate);
	}
	
	public boolean onCreateOptionsMenu(Menu menu) {
		mainMenu.createOptionsMenu(menu);
	    return true;
	}
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);
		return mainMenu.onItemSelected(item);	
	}
	
	private BroadcastReceiver updateRatesReceiver = new BroadcastReceiver() {		
		@Override
		public void onReceive(Context context, Intent intent) {
			Logger.logInfo("RATES: Broadcasted intent catched !");
			updateTitle();
			requestRates();
		}
	};
	private RequestableFrameLayout[] frames;
	private FrameLayout mainFrames;
	protected RateItem shareRate = null;
	private BroadcastReceiver updateGoldReceiver = new BroadcastReceiver() {
		
		@Override
		public void onReceive(Context context, Intent intent) {
			Logger.logInfo("GOLD: Broadcasted intent catched !");
			requestRates();
		}
	};
	protected SJCItem shareGoldPrice;
	
	static final private int[] tabResNormal = {R.drawable.global_currency_n, R.drawable.calculator_n, R.drawable.sms_n};
	static final private int[] tabResHighlight = {R.drawable.global_currency_o, R.drawable.calculator_o, R.drawable.sms_o};
	private static final String SHARE_RATE_ITEM = "SHARE_RATE";
	
	
	@Override
	protected void onResume() {	
		super.onResume();
		registerRateFilter();
		registerGoldFilter();
		requestRates();
	}

	private void registerGoldFilter() {
		IntentFilter ratesFilter = new IntentFilter();
		ratesFilter.addAction(UpdateGoldService.UPDATE_GOLD_INTENT);
		this.registerReceiver(this.updateGoldReceiver, ratesFilter);
		
	}

	private void registerRateFilter() {
		IntentFilter ratesFilter = new IntentFilter();
		ratesFilter.addAction(getString(R.string.UPDATE_RATE_BROADCAST_INTENT));
		this.registerReceiver(this.updateRatesReceiver, ratesFilter);
	}

	protected void requestRates() {
		DataProvider.getInstance().requestListRates(frames[currentTabId]);
		DataProvider.getInstance().requestGoldPrice(frames[currentTabId]);
	}

	@Override
	protected void onPause() {	
		super.onPause();
		this.unregisterReceiver(updateRatesReceiver);
		this.unregisterReceiver(updateGoldReceiver);
	}

	@Override
	protected void onStop() {	
		super.onStop();
		Intent i = new Intent(this,UpdateGoldService.class);
		stopService(i);
	}
	@Override
	protected void onSaveInstanceState(Bundle outState) {	
		super.onSaveInstanceState(outState);
		if ( shareRate != null )
			outState.putString(SHARE_RATE_ITEM, shareRate.toString());
	}
	
	private void createViews() {
		createTopLayout();
		loadLastSeenTab();
		createFrames();
		createBottomLayout();		
		onTabSelected(currentTabId);
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_LISTRATE_SHARE:
			return new ShareListRateDialog(this);
		case DIALOG_GOLD_SHARE:
			return new ShareGoldPriceDialog(this);
		}
		return super.onCreateDialog(id);
	}

	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		switch (id) {
		case DIALOG_LISTRATE_SHARE:
			((ShareListRateDialog) dialog).prepare(shareRate);
			break;
		case DIALOG_GOLD_SHARE:
			((ShareGoldPriceDialog) dialog).prepare(shareGoldPrice);
		}

		super.onPrepareDialog(id, dialog);
	}
	
	private void createFrames() {
		frames = new RequestableFrameLayout[NUM_TABS];
		mainFrames = (FrameLayout) findViewById(R.id.main_frames);
		for(int i = 0 ; i < NUM_TABS ; i++) {
			frames[i] = createFrame( i );	
			FrameLayout.LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT);
			if ( i == lastSeenTabId )
				frames[i].setVisibility(View.VISIBLE);
			else frames[i].setVisibility(View.INVISIBLE);
			mainFrames.addView(frames[i], params);
		}
	}

	
	private RequestableFrameLayout createFrame(int i) {
		RequestableFrameLayout frame = null;
		switch (i) { 
		case TAB_LST:
			frame = new ListRatesView(this) {
				@Override
				public void showShareDialog(RateItem rateItem) {
					shareRate = rateItem;
					showDialog(DIALOG_LISTRATE_SHARE);
				}

				@Override
				public void showShareGoldPriceDialog(SJCItem goldPrice) {
					shareGoldPrice = goldPrice;
					showDialog(DIALOG_GOLD_SHARE);
					
				}
			};
			break;
		case TAB_CAL:
			frame = new CalculatorView(this);
			break;
		case TAB_SMS:
			frame = new SendSmsView(this);
			break;
		}
		if ( frame != null ) 
			frame.createViews();
		return frame;
	}

	static final int[] TAB_IDS = { R.id.layoutTabListRates, R.id.layoutTabCalculator, R.id.layoutTabSendSms };
	static final int TAB_LST = 0;
	static final int TAB_CAL = 1;
	static final int TAB_SMS = 2;
	static final int NUM_TABS = 3;
	
	public static final int DIALOG_LISTRATE_SHARE = 0;
	protected static final int DIALOG_GOLD_SHARE = 1;
	
	private void createBottomLayout() {
		
		createBottomTabs();
	}

	private void loadLastSeenTab() {
		String lastTabIdStr = Helpers.getPreference(Helpers.PREF_LAST_TAB_ID);
		lastSeenTabId = TAB_LST;
		try {
			lastSeenTabId = Integer.parseInt(lastTabIdStr);
		} catch (Exception e) {}
		 
		currentTabId = lastSeenTabId;
	}

	private void createBottomTabs() {
		View layout = findViewById(R.id.bottom_tabs);
		tabs = new ImageButton[NUM_TABS]; 
		for(int i = 0 ; i < NUM_TABS ; i++) {
			createTab(i,layout);
		}
	}

	private void createTab(final int id, View layout) {
		tabs[id] = (ImageButton) layout.findViewById(TAB_IDS[id]);
		tabs[id].setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				if ( id != currentTabId ) {
					onTabSelected( id );
				}
			}

		});
	}
	
	private void onTabSelected(final int i) {
		highlightTab(i);
		if ( i == currentTabId ) return;
		if ( currentTabId == TAB_CAL && i != TAB_CAL ) {
			Helpers.hideSoftKeyboard(this,frames[currentTabId]);
		}

		InOutAnimation anim = new InOutAnimation(
				MyHandler.getInstance(),
				ApplicationContext.getContext()) 
		{
			@Override
			public void onNewViewDisplayed() {
				currentTabId = i;
				Helpers.setPreference(Helpers.PREF_LAST_TAB_ID, ""+currentTabId);
				requestRates();
			}
		};
		anim.startAnimations(
				frames[currentTabId], 
				frames[i], 
				getSlideOutAnim(currentTabId, i), 
				getSlideInAnim(currentTabId, i));
		
	}

	private int getSlideOutAnim(int currentTabId, int newTabId) {
		if (moveToLeft(currentTabId,newTabId)) {
			return R.anim.slide_out_right;
			
		} else return R.anim.slide_out_left; 
	}

	private int getSlideInAnim(int currentTabId, int newTabId) {
		if (moveToLeft(currentTabId,newTabId)) {
			return R.anim.slide_in_left;
		} else return R.anim.slide_in_right;	
	}
	//===================================== ANIMATIONS ====================
	
	protected void showOnlyView(int id) {	
		for(int i = 0 ; i < mainFrames.getChildCount() ; i++)
			if ( i == id) {
				 mainFrames.getChildAt(i).setVisibility(View.VISIBLE); 
			} else mainFrames.getChildAt(i).setVisibility(View.GONE);
		
	}

	
	private void highlightTab(int id) {
		for(int i = 0 ; i < NUM_TABS ; i++)
			if ( i == id ) {
				tabs[i].setImageResource(tabResHighlight[i]); 
			} else {
				tabs[i].setImageResource(tabResNormal[i]);
			}
	}



	private boolean moveToLeft(int oldId, int newId) {
		oldId--;
		if ( oldId < 0 ) oldId = NUM_TABS-1;
		if ( oldId == newId ) return true;
		return false;
	}

	private void updateTitle() {
		MyDate date = DataProvider.getInstance().getDate();
		tvTitle.setText(Html.fromHtml(getString(R.string.top_text_vcb_html)+" "+date.toString()));
		tvTitle.setMovementMethod(LinkMovementMethod.getInstance());
	}

	private void createTopLayout() {
		View layout = findViewById(R.id.top_layout);
		tvTitle = (TextView) layout.findViewById(R.id.tvTopTitle);
		updateTitle();
	}

	@Override
	protected void onSwipeLeft() {
		onTabSelected((currentTabId+1)%NUM_TABS);
	}
	
	@Override
	protected void onSwipeRight() {
		onTabSelected((currentTabId+NUM_TABS-1)%NUM_TABS);		
	}

	@Override
	public void onDoubleTap() {
		// TODO Auto-generated method stub
		
	}

}
